package com.itheima.service.impl;

import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.service.UserService;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper rolemapper;

    @Override
    public User login(String username, String password) {
        System.out.println("userService.login...");
        try {
            User user = userMapper.findByUsernameAndPassword(username, password);
            return user;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    public List<User> userList() {
        List<User> userList = userMapper.findAll();
        for (User user : userList) {
            Long id = user.getId();
            List<Role> roleList = rolemapper.findRoleById(id);
            user.setRoleList(roleList);
        }
        return userList;
    }

    @Override
    public void userSave(User user,Long[] roleIds) {
        userMapper.insert(user);
        Long userId = user.getId();
        for (Long roleId : roleIds) {
            userMapper.saveUserRoleRel(userId,roleId);
        }
    }

    @Override
    public void delete(Long userId) {
        userMapper.deleteUserRoleRel(userId);
        userMapper.delete(userId);
    }
}
